// v1.8.7
// 获取Node插件和工作路径
let ideModuleDir, workSpaceDir;
//是否使用IDE自带的node环境和插件，设置false后，则使用自己环境(使用命令行方式执行)
const useIDENode = process.argv[0].indexOf("LayaAir") > -1 ? true : false;
ideModuleDir = useIDENode ? process.argv[1].replace("gulp\\bin\\gulp.js", "").replace("gulp/bin/gulp.js", "") : "";
workSpaceDir = useIDENode ? process.argv[2].replace("--gulpfile=", "").replace("\\.laya\\publish_taobaogame.js", "").replace("/.laya/publish_taobaogame.js", "") + "/" : "./../";
//引用插件模块
const gulp = require(ideModuleDir + "gulp");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const childProcess = require("child_process");
const del = require(ideModuleDir + "del");
const revCollector = require(ideModuleDir + 'gulp-rev-collector');

let commandSuffix = ".cmd";

let
	config,
	releaseDir;
let isGlobalCli = true;
let isOpendataProj;
let versionCon; // 版本管理version.json
// 应该在publish中的，但是为了方便发布2.0及IDE 1.x，放在这里修改
gulp.task("preCreate_WX", function () {
	let pubsetPath = path.join(workSpaceDir, ".laya", "pubset.json");
	let content = fs.readFileSync(pubsetPath, "utf8");
	let pubsetJson = JSON.parse(content);
	releaseDir = path.join(workSpaceDir, "release", "taobaogame").replace(/\\/g, "/");
	config = pubsetJson[14];
	if (process.platform === "darwin") {
		commandSuffix = "";
	}

	return;
});
gulp.task("moveTemprelease", ["preCreate_WX"], function () {
	const tempreleaseDir = path.join(releaseDir, "temprelease");
	if (fs.existsSync(tempreleaseDir)) {
		//遍历tempreleaseDir下的所有文件及文件夹
		const files = fs.readdirSync(tempreleaseDir);
		files.forEach(async file => {
			const filePath = path.join(tempreleaseDir, file);
			const stat = fs.statSync(filePath);
			if (stat.isDirectory()) {
				//移动这个文件夹以及所有文件到releaseDir下
				const distDir = path.join(releaseDir, file);
				if (fs.existsSync(distDir)) {
					fs.rmdirSync(distDir, { recursive: true });
				}
				fs.renameSync(filePath, distDir);
			} else {
				//如果是文件，则移动到releaseDir下
				fs.renameSync(filePath, path.join(releaseDir, file));
			}
		});
	}
	//移除tempreleaseDir
	del(tempreleaseDir, { force: true });
});


gulp.task("copyPlatformFile_WX", ["moveTemprelease"], function () {
	let adapterPath = path.join(ideModuleDir, "../", "out", "layarepublic", "LayaAirProjectPack", "lib", "data", "taobaominigame", 'minigame');
	// let hasPublishPlatform =
	// 	fs.existsSync(path.join(releaseDir, "game.js")) &&
	// 	fs.existsSync(path.join(releaseDir, "game.json")) &&
	// 	fs.existsSync(path.join(releaseDir, "mini.project.json")) &&
	// 	fs.existsSync(path.join(releaseDir, "my-adapter.js"));
	// if (hasPublishPlatform) {
	// 	copyLibsList = [`${adapterPath}/my-adapter.js`];
	// } else {
	copyLibsList = [`${adapterPath}/*.*`];
	// }
	let stream = gulp.src(copyLibsList);
	return stream.pipe(gulp.dest(releaseDir));
});
gulp.task("modifyMinJs_TBMini", ["copyPlatformFile_WX"], function () {
	// let dirPath = path.join(releaseDir, "libs", "min");
	// let filePath = path.join(releaseDir, "game.js");
	// let content = fs.readFileSync(filePath, 'utf-8');
	// if (fs.existsSync(dirPath)) {
	// 	content = modifyTemplateString(content, { tbmini: "./libs/min/laya.tbmini.min.js" });

	// } else {
	// 	content = modifyTemplateString(content, { tbmini: "./libs/laya.tbmini.js" });
	// }
	// fs.writeFileSync(filePath, content, 'utf-8');

});
function modifyTemplateString(template, replacements) {
	let modifiedString = template;
	for (let key in replacements) {
		modifiedString = modifiedString.replace(`{${key}}`, replacements[key]);
	}
	return modifiedString;
}
function modifyAllJSFun(coreJsPath) {
	if (fs.existsSync(coreJsPath)) {
		let content = fs.readFileSync(coreJsPath, 'utf-8');
		//把所有的laya.替换成window.laya.除了"laya.和'laya.

		// 使用正则表达式配合回调函数来精确替换
		content = content.replace(/laya\./g, function (match, offset, string) {
			// 检查这个laya.是否在字符串内
			let beforeMatch = string.substring(0, offset);
			let afterMatch = string.substring(offset + match.length);

			// 计算前面的引号数量
			let singleQuotes = (beforeMatch.match(/'/g) || []).length;
			let doubleQuotes = (beforeMatch.match(/"/g) || []).length;
			let backticks = (beforeMatch.match(/`/g) || []).length;

			// 如果引号数量是奇数，说明在字符串内
			if (singleQuotes % 2 === 1 || doubleQuotes % 2 === 1 || backticks % 2 === 1) {
				return match; // 不替换
			}

			// 检查前面是否是有效的开始位置
			let prevChar = beforeMatch[beforeMatch.length - 1];
			let isValidStart = !prevChar ||
				/[\s\(\[\{;=,+\-*\/%&|^!~<>?:]/.test(prevChar) ||
				prevChar === '\n' ||
				prevChar === '\t' ||
				prevChar === '\r';

			if (isValidStart) {
				return 'window.laya.';
			} else {
				return match; // 不替换
			}
		});

		fs.writeFileSync(coreJsPath, content, 'utf-8');
	}
}
gulp.task("modifyCoreJs", ["modifyMinJs_TBMini"], function () {
	// const coreJsPath = path.join(releaseDir, "libs", "laya.core.js");
	// modifyAllJSFun()
	//遍历releaseDir下的所有js文件，包括子文件夹中的js文件
	const walkDir = (dir) => {
		let results = [];
		const list = fs.readdirSync(dir);
		list.forEach(file => {
			const filePath = path.join(dir, file);
			const stat = fs.statSync(filePath);
			if (stat && stat.isDirectory()) {
				results = results.concat(walkDir(filePath));
			} else if (file.endsWith('.js')) {
				results.push(filePath);
			}
		});
		return results;
	};

	const jsFiles = walkDir(path.join(releaseDir, "libs"));
	jsFiles.forEach(filePath => {
		modifyAllJSFun(filePath);
	});
});

gulp.task("modifyAllJS", ["modifyCoreJs"], function () {
	//遍历releaseDir下的所有js文件，包括子文件夹中的js文件
	const walkDir = (dir) => {
		let results = [];
		const list = fs.readdirSync(dir);
		list.forEach(file => {
			const filePath = path.join(dir, file);
			const stat = fs.statSync(filePath);
			if (stat && stat.isDirectory()) {
				results = results.concat(walkDir(filePath));
			} else if (file.endsWith('.js')) {
				results.push(filePath);
			}
		});
		return results;
	};

	const jsFiles = walkDir(path.join(releaseDir, "libs"));
	jsFiles.push(path.join(releaseDir, "code.js"));

	jsFiles.forEach(filePath => {
			let content = fs.readFileSync(filePath, 'utf-8');
			content = `var window = $global;
	var Laya = window.Laya;
	var laya = window.laya;
	var performance = window.performance;
	var navigator = window.navigator;
	var spine = window.spine;
	var document = window.document;
	var loadLib = require;
	var Config = window.Config;
	var Laya3D = window.Laya3D;
			`+ content;
			fs.writeFileSync(filePath, content, 'utf-8');
	});

});



gulp.task("buildTBGameProj", ["modifyAllJS"], function () {
	console.log("all tasks completed");
});